package com.moli.iov.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.base.cache.redis.VehicleAttentionCacheService;
import com.moli.iov.base.cache.redis.VehicleFollowGroupCacheService;
import com.moli.iov.base.enums.YesOrNoEnum;
import com.moli.iov.base.mapper.VehicleAttentionMapper;
import com.moli.iov.base.mapper.VehicleFollowGroupMapper;
import com.moli.iov.base.model.VehicleAttentionParam;
import com.moli.iov.base.model.dto.req.VehicleAttentionReqDto;
import com.moli.iov.base.model.dto.req.VehicleFollowGroupReqDto;
import com.moli.iov.base.model.po.VehicleAttention;
import com.moli.iov.base.model.po.VehicleFollowGroup;
import com.moli.iov.base.service.IVehicleAttentionService;
import com.moli.iov.base.service.IVehicleFollowGroupService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 车辆关注组表  服务实现类
 * </p>
 *
 * @author OAK
 * @since 2020/2/20 09:42 AM.
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class VehicleFollowGroupServiceImpl extends
    ServiceImpl<VehicleFollowGroupMapper, VehicleFollowGroup> implements IVehicleFollowGroupService {

  @Autowired
  private VehicleFollowGroupCacheService vehicleFollowGroupCacheService;

  @Autowired
  private IVehicleAttentionService vehicleAttentionService;

  @Override
  public RestResponse save(VehicleFollowGroupReqDto vehicleFollowGroupReqDto) {
    log.info("车辆监控-车辆管理-添加关注组入参VehicleFollowGroupReqDto:{}" + vehicleFollowGroupReqDto);
    if (vehicleFollowGroupReqDto == null) {
      log.info("车辆监控-车辆管理-添加关注组入参失败：参数为空");
      return RestResponse.failure("参数为空");
    }

    Map<Long, String> vehicleFollowGroupMap = this.findNameByUserId(vehicleFollowGroupReqDto.getUserId());
    if(vehicleFollowGroupMap!=null && vehicleFollowGroupMap.values().contains(vehicleFollowGroupReqDto.getGroupName())){
      log.info("车辆监控-车辆管理-添加关注组入参失败：关注组名称已存在");
      return RestResponse.failure("关注组名称已存在");
    }

    VehicleFollowGroup vehicleFollowGroup = new VehicleFollowGroup();
    BeanUtils.copyProperties(vehicleFollowGroupReqDto, vehicleFollowGroup);
    vehicleFollowGroup.setIsDelete(YesOrNoEnum.NO.getCode());
    log.info("车辆监控-车辆管理-添加关注组：入库数据：{}",vehicleFollowGroup.toString());
    boolean save = this.save(vehicleFollowGroup);
    if (save) {
      log.info("车辆监控-车辆管理-添加关注组：初始化缓存");
      Set<String> vins = vehicleAttentionService.findByUserIdAndGroupId(vehicleFollowGroup.getUserId(), vehicleFollowGroup.getId());
      if(vins!=null && vins.size()>0){
        vehicleFollowGroupCacheService.set(vehicleFollowGroup.getId(), vehicleFollowGroup.getUserId(), vins);
      }
      log.info("车辆监控-车辆管理-添加关注组：操作成功");
      return RestResponse.success("操作成功");
    } else {
      log.info("车辆监控-车辆管理-添加关注组：入库失败");
      return RestResponse.failure("添加失败");
    }
  }


  @Deprecated
  @Override
  public RestResponse saveOrUpdate(VehicleFollowGroupReqDto vehicleFollowGroupReqDto) {
    log.info("车辆监控-车辆管理-修改关注组入参VehicleFollowGroupReqDto:{}" + vehicleFollowGroupReqDto);
    if (vehicleFollowGroupReqDto == null) {
      return RestResponse.failure("参数为空");
    }
    //淘汰缓存
    QueryWrapper<VehicleFollowGroup> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("is_delete", 0);
    Long userId = vehicleFollowGroupReqDto.getUserId();
    if (userId != null) {
      queryWrapper.eq("user_id", userId);
    }
    List<VehicleFollowGroup> vehicleFollowGroupList = list(queryWrapper);
    vehicleFollowGroupCacheService.eviction(userId, vehicleFollowGroupList.stream().map(vehicleFollowGroup -> vehicleFollowGroup.getId().toString()).collect(Collectors.toSet()));
    VehicleFollowGroup vehicleFollowGroup = new VehicleFollowGroup();
    CommonUtils.copyProperties(vehicleFollowGroupReqDto, vehicleFollowGroup);
    boolean save = this.saveOrUpdate(vehicleFollowGroup);
    if (save) {
      if (vehicleFollowGroup.getIsDelete().intValue() == YesOrNoEnum.NO.getCode()) {
        vehicleFollowGroupList.forEach((group) ->
                vehicleFollowGroupCacheService.set( group.getId(),userId, vehicleAttentionService.findByUserIdAndGroupId(userId, group.getId()))
        );
      }
      return RestResponse.success();
    } else {
      return RestResponse.failure("添加失败");
    }
  }

  @Override
  public Map<Long, String> findNameByUserId(Long userId){
    QueryWrapper<VehicleFollowGroup> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("is_delete", 0);
    if (userId != null) {
      queryWrapper.eq("user_id", userId);
    }
    List<VehicleFollowGroup> vehicleFollowGroupList = list(queryWrapper);
    return vehicleFollowGroupList.stream().collect(Collectors.toMap(VehicleFollowGroup::getId, VehicleFollowGroup::getGroupName));
  }

  @Override
  public Map<String, Set<String>> findVehicleFollowGroupByUserId(Long userId) {
    Map<String, Set<String>> vehicleFollowGroupMap = vehicleFollowGroupCacheService.findByUserId(userId);
    if (vehicleFollowGroupMap != null && !vehicleFollowGroupMap.isEmpty()) {
      return vehicleFollowGroupMap;
    } else {
      QueryWrapper<VehicleFollowGroup> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("is_delete", 0);
      if (userId != null) {
        queryWrapper.eq("user_id", userId);
      }
      List<VehicleFollowGroup> vehicleFollowGroupList = list(queryWrapper);
      if (vehicleFollowGroupList != null && !vehicleFollowGroupList.isEmpty()) {
        vehicleFollowGroupList.stream().forEach(vehicleFollowGroup ->
                vehicleFollowGroupCacheService.set(vehicleFollowGroup.getId(), userId,
                        vehicleAttentionService.findByUserIdAndGroupId(userId, vehicleFollowGroup.getId())));
          return vehicleFollowGroupCacheService.findByUserId(userId);
      }
      return null;
    }
  }

  @Override
  public void init() {
    //清空缓存
    vehicleFollowGroupCacheService.clear();
    QueryWrapper<VehicleFollowGroup> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("is_delete", 0);
    List<VehicleFollowGroup> list = list(queryWrapper);
    if (!CollectionUtils.isEmpty(list)) {
      Map<Long, List<VehicleFollowGroup>> collect = list.stream()
          .collect(Collectors.groupingBy(VehicleFollowGroup::getUserId));
      collect.forEach(
              (userId, followGroups) ->
                      followGroups.forEach((followGroup) ->
                              vehicleFollowGroupCacheService.set(followGroup.getId(), userId, vehicleAttentionService.findByUserIdAndGroupId(userId, followGroup.getId()))
                      )
      );
    }
  }

  @Deprecated
  @Override
  public void batch(List<VehicleFollowGroup> list, Long userId, ModelStatus status) {
    if (CollectionUtils.isEmpty(list)) {
      throw new BusinessException("参数为空");
    }
    boolean executionStatus = false;
    if(status.compareTo(ModelStatus.SAVE) == 0){
      executionStatus = saveBatch(list);
    }else if(status.compareTo(ModelStatus.DELETE) == 0){
      executionStatus = saveOrUpdateBatch(list);
    }
    Set<Long> collect = null;
    if (executionStatus) {
      collect = list.stream().map(VehicleFollowGroup::getId).collect(Collectors.toSet());
    }
    if(status.compareTo(ModelStatus.SAVE) == 0){
      collect.forEach((groupId) ->
              vehicleFollowGroupCacheService.set(groupId, userId, vehicleAttentionService.findByUserIdAndGroupId(userId, groupId))
      );
    }else if(status.compareTo(ModelStatus.DELETE) == 0){
      vehicleFollowGroupCacheService.eviction(userId, collect.stream().map(c -> c.toString()).collect(Collectors.toSet()));
    }
  }

  @Override
  public List<VehicleFollowGroup> findByUserId(Long userId) {
    if (CollectionUtils.isEmpty(userId)){
      throw new BusinessException("userId不能为空");
    }
    QueryWrapper<VehicleFollowGroup> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("is_delete", 0);
    if (userId != null) {
      queryWrapper.eq("user_id", userId);
    }
    return list(queryWrapper);
  }

}
